package com.ghy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ghy.dto.CommentInsertDTO;
import com.ghy.dto.CommentPageDTO;
import com.ghy.dto.CommentUpdateDTO;
import com.ghy.entity.User;
import com.ghy.exception.ServiceException;
import com.ghy.feign.UserFeign;
import com.ghy.result.Result;
import com.ghy.vo.CommentSimpleListVO;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.ghy.entity.Comment;
import com.ghy.mapper.CommentMapper;
import com.ghy.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

import static com.ghy.entity.table.CommentTableDef.COMMENT;
import static com.ghy.entity.table.MenuTableDef.MENU;
import static com.ghy.entity.table.RoleMenuTableDef.ROLE_MENU;
import static com.ghy.entity.table.SeckillDetailTableDef.SECKILL_DETAIL;

/**
 * 评论表 服务层实现。
 *
 * @author ghy
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "comment")
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>  implements CommentService{


    @Autowired
    private UserFeign userFeign;

    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(CommentInsertDTO dto) {
        //组装entity 实体类
        Comment comment = BeanUtil.copyProperties(dto, Comment.class);
        User user = userFeign.select(dto.getFkUserId()).getData();
        if (ObjectUtil.isNull(user)){
            throw new RuntimeException("用户不存在");
        }

        comment.setNickname(user.getNickname());
        comment.setCreated(LocalDateTime.now());
        comment.setUpdated(LocalDateTime.now());

        return mapper.insert(comment) > 0;
    }

    @Cacheable(key = "#p0",
            condition = "#p0 != null",
            unless = "#result == null")
    @Override
    public Comment select(Long id) {
        RelationManager.addQueryRelations("episode");
        return mapper.selectOneWithRelationsById(id);
    }

    @Cacheable(key = "#root.methodName",
            unless = "#result == null")
    @Override
    public List<CommentSimpleListVO> simpleList() {
        return QueryChain.of(mapper)
                .withRelations ()
                .listAs(CommentSimpleListVO.class);
    }

    @Cacheable(key ="#root.methodName + ':' + #p0.toString()",
            condition = "#p0 != null",
            unless = "#result == null")
    @Override
    public Page<Comment> page(CommentPageDTO dto) {
        QueryChain<Comment> queryChain = QueryChain.of(mapper);

        //pid条件
        Long pid=dto.getPid();
        if (ObjectUtil.isNotNull(pid)){
            queryChain.where(COMMENT.PID.eq(pid));
        }

        //episodeId条件
        Long episodeId = dto.getFkEpisodeId();
        if (ObjectUtil.isNotNull(episodeId)){
            queryChain.where(COMMENT.FK_EPISODE_ID.eq(episodeId));
        }

        //userId条件
        Long userId = dto.getFkUserId();
        if (ObjectUtil.isNotNull(userId)){
            queryChain.where(COMMENT.FK_USER_ID.eq(userId));
        }

        return queryChain.withRelations()
                .page(new Page<>(dto.getPageNum(),dto.getPageSize()));
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean update(CommentUpdateDTO dto) {
        //组装entity实体类
        Comment comment = BeanUtil.copyProperties(dto, Comment.class);
        Result<User> user = userFeign.select(dto.getFkUserId());
        if (ObjectUtil.isNull(user)){
            throw new RuntimeException("用户不存在");
        }
        comment.setNickname(user.getData().getNickname());
        comment.setUpdated(LocalDateTime.now());

        return UpdateChain.of(comment)
                .where(COMMENT.ID.eq(comment.getId()))
                .update();
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {

        // 查询父菜单ID和全部子菜单ID
        // select id from menu where pid = 1 or id = 1
        List<Long> ids = QueryChain.of(mapper)
                .select(COMMENT.ID)
                .where(COMMENT.PID.eq(id))
                .or(COMMENT.ID.eq(id))
                .objListAs(Long.class);

        // 删除 MENU 表中的菜单
        // delete from menu where id in(?)
        return UpdateChain.of(mapper)
                .where(COMMENT.ID.in(ids))
                .remove();

    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {
        List<Long> idss = QueryChain.of(mapper)
                .select(COMMENT.ID)
                .where(COMMENT.PID.in(ids))
                .or(COMMENT.ID.in(ids))
                .objListAs(Long.class);

        // 删除 MENU 表中的菜单
        // delete from menu where id in(?)
        return UpdateChain.of(mapper)
                .where(COMMENT.ID.in(idss))
                .remove();
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public  boolean deleteByUserId(Long userId){

        // 查询该用户的所有评论ID列表
        List<Long> commentIds = QueryChain.of(mapper)
                .select(COMMENT.ID)
                .where(COMMENT.FK_USER_ID.eq(userId))
                .listAs(Long.class);

        // 无评论记录
        if (CollUtil.isEmpty(commentIds)) {
            return true;
        }

        // 查询子评论ID列表
        List<Long> subCommentIds = QueryChain.of(mapper).select(COMMENT.ID)
                .where(COMMENT.PID.in(commentIds))
                .listAs(Long.class);

        // 组合父评论和子评论的ID列表
        if (CollUtil.isNotEmpty(subCommentIds)) {
            commentIds.addAll(subCommentIds);
        }

        // 删除评论
        return mapper.deleteBatchByIds(commentIds) > 0;

    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public  boolean deleteByUserIds(List<Long> userIds){

       List<Long> commentIds = QueryChain.of(mapper)
                .select(COMMENT.ID)
                .where(COMMENT.FK_USER_ID.in(userIds))
                .objListAs(Long.class);

        if (CollUtil.isEmpty(commentIds)){
            return true;
        }

        List<Long> ids = QueryChain.of(mapper)
                .select(COMMENT.ID)
                .where(COMMENT.PID.in(commentIds))
                .or(COMMENT.ID.in(commentIds))
                .objListAs(Long.class);


        return UpdateChain.of(mapper)
                .where(COMMENT.ID.in(ids))
                .remove();
    }
}
